package com.dcy.singleton.type6;

/**
 * @Author：dcy
 * @Description:
 * @Date: 2021/1/19 14:45
 */
public class SingletonTest06 {
    public static void main(String[] args) {
        // 测试
        System.out.println("双重检查");
        Singleton instance = Singleton.getInstance();
        Singleton instance2 = Singleton.getInstance();
        System.out.println(instance == instance2);
        System.out.println(instance.hashCode());
        System.out.println(instance2.hashCode());
    }
}



/**
 * 双重检查
 */
class Singleton {

    // volatile 会立即更新到主存
    private static volatile Singleton singleton;

    private Singleton() {
    }

    // 提供一个静态的公有方法，加入双重检查代码，解决线程安全问题，同时解决懒加载问题
    // 同时保证了效率，推荐使用
    public static Singleton getInstance() {
        if (singleton == null) {
            synchronized (Singleton.class){
                if (singleton == null){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}